import os
from pptx import Presentation
import requests
import json
import re
import sys
from urllib.parse import unquote
import base64
import logging
from logging.handlers import RotatingFileHandler
import PyPDF2

logger = logging.getLogger('my_logger')
logger.setLevel(logging.INFO)

handler = RotatingFileHandler('app.log', maxBytes=10*1024*1024, backupCount=3)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

# remote
url = "http://noco.junroumall.com/api/v2/tables/m4a3zd7avcnudtq/records"
headers = {
    'Content-Type': 'application/json',
    'xc-token': 'G45R5ax8MbBkcfoEwptyRTMQmtaUyZr9CGYxcj76'
    # 'xc-auth': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6IjI2MzE5ODE2QHFxLmNvbSIsImlkIjoidXNpOTZqcnZyamRleXAxYSIsInJvbGVzIjoib3JnLWxldmVsLWNyZWF0b3Isc3VwZXIiLCJ0b2tlbl92ZXJzaW9uIjoiNjA0YWQwOWY2MWZlODg2ZDJiY2E3ODE2ZjA1MzEzMmRhMjg2MTJlYWZkZWM0MjE4ZDI4MmEzN2E0MWEyMWQzN2FhNDc0YzdmZjk1MzFkZjQiLCJpYXQiOjE3MDU2MjcwMjcsImV4cCI6MTcwNTY2MzAyN30._EvjJ3DJzzobP5AsKSWhQaAbvjViA4y5hwiClguSp-Q'
}

# localhost
# url = "http://192.168.1.110:8080/api/v2/tables/ma3b90h632tqexf/records"
# headers = {
# 	'Content-Type': 'application/json',
# 	'xc-auth': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6IjI2MzE5ODE2QHFxLmNvbSIsImlkIjoidXM3N2xjN3RkODFpcWZ3bSIsInJvbGVzIjp7Im9yZy1sZXZlbC1jcmVhdG9yIjp0cnVlLCJzdXBlciI6dHJ1ZX0sInRva2VuX3ZlcnNpb24iOiI2ZjY2OGQwNWMwMmZkNDM2NGQ1M2VhYWRlNzZkNTU1ZmMzMWM2NjcyMWExYTg4ZTQwNjE3MDUzMzI3NTM3MGI0NWVjOTdmY2YwOThjMzA2MiIsImlhdCI6MTcwNTU0MzQ2NCwiZXhwIjoxNzA1NTc5NDY0fQ.62I4oUKEjvxJVwx08eOcq0YtIp-OElEptsr_tjg9Al0'
# }

def extract_text_from_slide(slide):
	text_list = []
	for shape in slide.shapes:
		if shape.has_text_frame:
			# print('@@', shape.text_frame.text)
			text = ""
			for paragraph in shape.text_frame.paragraphs:
				if not paragraph.text: continue
				# text_list.append(paragraph.text)
				text += re.sub(r'\s+', '', paragraph.text)
				# for run in paragraph.runs:
				# 	if run.text != "":
				# 		text += run.text
			if not text: continue
			# print('@@', text)
			text_list.append(text)
	return text_list

def extract_images_from_slide(slide):
	images = []
	for shape in slide.shapes:
		if shape.shape_type == 13:
			image = shape.image
			images.append(image)
	return images

def search_text_in_presentation(presentation, search_text):
	for i, slide in enumerate(presentation.slides):
		text = extract_text_from_slide(slide)
		if search_text in text:
			return i
	return -1
	
def extract_text_from_pdf(file_path):
    with open(file_path, 'rb') as file:
        pdf_reader = PyPDF2.PdfReader(file)
        text_list = []
        for page_number, page in enumerate(pdf_reader.pages, 1):
            page_text = page.extract_text()
            non_empty_lines = [line for line in page_text.split('\n') if line.strip()]
            if non_empty_lines:
                data = {
                    "index": page_number,
                    "text": "".join(non_empty_lines)
                }
                text_list.append(data)
    return text_list

# def search(query, documents):
# 	scores = []
# 	for doc in documents:
# 		score = difflib.SequenceMatcher(None, doc.split(), query.split()).ratio()
# 		scores.append((score, doc))
# 	scores.sort(reverse=True)
# 	return scores
print(sys.argv)

encoded_file_name = sys.argv[1]
decoded_file_name = unquote(encoded_file_name, encoding='utf-8')
logger.info('file_name: {}'.format(decoded_file_name))
# file_path = os.path.join('./uploads', decoded_file_name)
# file_path = sys.argv[2]
remote_file_path = os.path.join('https://imgs.junroumall.com/', decoded_file_name)
local_file_path = os.path.join("./uploads/", decoded_file_name)
print("remote_file_path: ", remote_file_path)
print("local_file_path: ", local_file_path)

# output_dir = "output"
# os.makedirs(output_dir, exist_ok=True)

def extract_text_from_pptx(file_path):
    presentation = Presentation(file_path)
    my_text_list = []
    for i, slide in enumerate(presentation.slides):
    	text = extract_text_from_slide(slide)
    
    	if not text:
    		continue
    
    	text_json = json.dumps(text, ensure_ascii=False)
    
    	data = {
    		"index": i,
    		"text": text_json
    	}
    	my_text_list.append(data)
    return my_text_list
    
def get_file_extension(file_path):
    _, file_extension = os.path.splitext(file_path)
    return file_extension
    
text_list = []    
file_extension = get_file_extension(decoded_file_name)
if file_extension == '.pdf' or file_extension == '.pptx':
    # download file to local
    down_response = requests.get(remote_file_path)
    with open(local_file_path, 'wb') as f:
        f.write(down_response.content)


if file_extension == '.pdf':
    text_list = extract_text_from_pdf(local_file_path)
elif file_extension == '.pptx':
    text_list = extract_text_from_pptx(local_file_path)
else:
    print('Unsupported file types')

# after parse remove local file
os.remove(local_file_path)

if len(text_list) == 0:
    print('Unsupported file types')
else:
    file_name = os.path.splitext(decoded_file_name)[0]
    
    file_name = file_name.replace('supplier/', '')
    
    submit_data = {
    	"Title": file_name,
    	"content": json.dumps(text_list, ensure_ascii=False),
    	"path": remote_file_path
    }
    json_data = json.dumps(submit_data)
    response = requests.post(url, data=json_data, headers=headers)
    if response.status_code == 200:
    	print('request success', response.text)
    else:
    	print('request faild', response.text)
# json_data = json.dumps(submit_data, ensure_ascii=False)
# print(json_data)
# json_data = json.dumps(submit_data, ensure_ascii=False, escapechar='\\')
# json_data = json.dumps(submit_data)
# print(json_data)
# print(f'index: {i}, text: {text}')

	# page_dir = os.path.join(output_dir, str(i + 1))
	# os.makedirs(page_dir, exist_ok=True)

	# upload_imgs = []

	# for imgi, image in enumerate(images):

	# 	image_file = os.path.join(page_dir, f"image_{i}.png")
	# 	with open(image_file, "wb") as f:
	# 		f.write(image.blob)

	# 	image_info = {
	# 		"title": image.filename,
	# 		"mimetype": image.content_type,
	# 		"size": os.path.getsize(image_file),
	# 		"path": image_file
	# 	}
	# 	upload_imgs.append(image_info)

	# data = {
	# 	"Title": i,
	# 	"title5": upload_imgs
	# }
	# json_data = json.dumps(data)